<template>
  <div class="app-container">
    <!-- 表格-条件筛区域  -->
    <div class="filter-container">
      <el-input placeholder="请输入手机号" v-model="searchParam.SEARCH_LIKE_mobile" clearable style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input placeholder="请输入用户名" v-model="searchParam.SEARCH_LIKE_username" clearable style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-input placeholder="请输入真实姓名" v-model="searchParam.SEARCH_LIKE_real_name" clearable style="width: 200px;"
                class="filter-item" @keyup.enter.native="handleFilter"/>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleFilter"> 搜索</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleImport"  > 导入</el-button>
      <el-button class="filter-item" type="primary" icon="el-icon-search" @click="handleExcel"> 下载导入模版</el-button>
      <p class="filter-item"> 导入的用户默认密码为手机号后6位</p>
<!--      <el-button class="filter-item" style="margin-left: 10px;" type="primary" icon="el-icon-plus"-->
<!--                 @click="handleCreate"> 新增-->
<!--      </el-button>-->
    </div>

    <!-- 表格-内容区域 -->
    <el-table v-loading="listLoading" :key="tableKey" :data="tableList" border fit highlight-current-row
              style="width: 100%;">
      <el-table-column v-for="column in columns" :key="column.prop"
                       :prop="column.prop"
                       :label="column.label"
                       :width="column.width"
                       :align="column.align?column.align:'center'"
                       :min-width="column.minWidth"
                       :sortable="column.sortable"
                       :fixed="column.fixed"
                       :type="column.type" :formatter="column.formatter">
        <template slot-scope="scope">
          <!-- 行内显示图片 -->
          <img v-if="column.imgFlag==true && scope.row[column.prop]"
               :src=" scope.row[column.prop].indexOf('http') >-1 ?  scope.row[column.prop] : ( CMBASE.baseFileContext + scope.row[column.prop] ) "
               width="60" height="60" class="img"/>
          <!-- 行内显示开关按钮 -->
          <el-switch v-else-if="column.switchFlag==true" v-model="scope.row[column.prop]" :active-value="1"
                     :inactive-value="0" disabled/>
          <!-- 行内显示tag标签 -->
          <span v-else-if="column.tagFlag==true">
                        <span v-for="item in column.tagFormatter" :key="item.value">
                            <el-tag v-if="item.value==scope.row[column.prop]" :type="item.type">{{ item.text }}</el-tag>
                        </span>
                    </span>
          <!-- 行内格式自定义 -->
          <span v-else-if="column.formatter"> {{ column.formatter(scope.row) }}</span>
          <!--默认显示文本-->
          <span v-else>{{ scope.row[column.prop] }}</span>
        </template>
      </el-table-column>

      <el-table-column label="操作" align="center" width="240" class-name="small-padding">
        <template slot-scope="scope">
          <div>
            <el-button type="text" icon="el-icon-edit" class="el-button--primary" @click="handleUpdate(scope.row)"> 编辑
            </el-button>
            <el-button type="text" icon="el-icon-delete" class="el-button--danger" @click="handleDelete(scope.row)">
              删除
            </el-button>
          </div>
         <!--<div>
           <el-button type="text" icon="el-icon-delete" class="el-button--danger" @click="handleCertificate(scope.row)">
             认证申请
           </el-button>
           <el-button type="text" icon="el-icon-delete" class="el-button--danger" @click="handleCoupon(scope.row)">
             优惠券申请
           </el-button>
         </div>-->
        </template>
      </el-table-column>
    </el-table>

    <!-- 表格-页脚区域 -->
    <pagination v-show="tableTotal>0" :total="tableTotal" :page.sync="pageRequest.pageNum"
                :limit.sync="pageRequest.pageSize" @pagination="getList"/>

    <!--新增编辑界面-->
    <el-dialog :title="operation?'新增':'编辑'" width="45%" top="5vh" :visible.sync="dialogFormVisible"
               :close-on-click-modal="false">
      <el-form :model="dataForm" label-width="140px" :rules="dataFormRules" ref="dataForm" style="width: 80%">

        <el-form-item label="用户名" prop="username">
          <el-input v-model="dataForm.username" auto-complete="off" placeholder="请输入用户名"/>
        </el-form-item>
        <el-form-item label="手机号" prop="mobile">
          <el-input v-model="dataForm.mobile" auto-complete="off" placeholder="请输入手机号"/>
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="dataForm.email" auto-complete="off" placeholder="请输入邮箱"/>
        </el-form-item>
        <el-form-item label="用户状态" prop="state">
          <el-switch v-model="dataForm.state" :active-value="1"
                     :inactive-value="2"></el-switch>
        </el-form-item>
        <el-form-item label="用户编号" prop="userNo">
          <el-input v-model="dataForm.userNo" auto-complete="off" placeholder="请输入用户编号"/>
        </el-form-item>
        <el-form-item label="用户头像" prop="headPic">
          <cm-upload v-model="dataForm.headPic"></cm-upload>
        </el-form-item>
        <el-form-item label="真实昵称" prop="realName">
          <el-input v-model="dataForm.realName" auto-complete="off" placeholder="请输入真实昵称"/>
        </el-form-item>
        <el-form-item label="证件号" prop="idCard">
          <el-input v-model="dataForm.idCard" auto-complete="off" placeholder="请输入证件号"/>
        </el-form-item>
        <el-form-item label="添加时间" prop="createTime">
          <el-date-picker type="date" placeholder="选择日期" v-model="dataForm.createTime"
                          value-format="yyyy-MM-dd"
                          style="width: 100%;"></el-date-picker>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeDialog()">取消</el-button>
        <el-button size="mini" @click.native="saveFormData()" :loading="editLoading" type="primary">提交</el-button>
      </div>
    </el-dialog>

    <!--   文件导入-->
    <el-dialog title="导入" width="30%" top="5vh" :visible.sync="dialogImportVisible"
               :close-on-click-modal="false">
      <el-upload
          v-if="dialogImportVisible"
          class="upload-demo"
          drag
          accept=".xlsx,.xls,.xlsm,.xlsb,.csv"
          :on-success="UploadSuccess"
          :file-list="importFile"
          :action="CMBASE.baseUploadUserExcelAction"
          multiple>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text" >将文件拖到此处，或<em>点击上传</em></div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="closeImportDialog()">关闭</el-button>
      </div>
    </el-dialog>


    <el-dialog
      title="认证申请"
      width="65%" top="5vh" :visible.sync="dialogCertificate" :close-on-click-modal="false"
    >
      <certificate-user v-if="dialogCertificate"  :did="did" ></certificate-user>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogCertificate=false">取消</el-button>
      </div>

    </el-dialog>


    <el-dialog
        title="认证申请"
        width="65%" top="5vh" :visible.sync="dialogCoupon" :close-on-click-modal="false"
    >
      <user-coupon v-if="dialogCoupon"  :did="did" ></user-coupon>
      <div slot="footer" class="dialog-footer">
        <el-button size="mini" @click.native="dialogCoupon=false">取消</el-button>
      </div>

    </el-dialog>


  </div>
</template>
<script>
import Pagination from '@/components/Pagination' // 分页栏信息
import CmUpload from '@/components/CmUpload' // 上传图片组件引入
import CertificateUser from "./certificateUser.vue";
import UserCoupon from "./userCoupon.vue"
import moment from 'moment';

export default {
  name: 'userInfo',
  components: {
    Pagination,
    CmUpload,
    CertificateUser,
    UserCoupon,
  },
  directives: {},
  filters: {},
  data() {
    return {
      did:'',

      tableKey: 0,
      tableList: [],//表格数据源
      tableTotal: 0,//表格总条数数据
      listLoading: true,
      pageRequest: {pageNum: 1, pageSize: 10,},
      searchParam: {},
      importFile: [],
      orderParam: {
        create_time: false,
        user_no:false,
      },
      dialogFormVisible: false,//默认不显示弹出框
      operation: true, // true:新增, false:编辑
      editLoading: false,//保存表单时loading框
      dialogImportVisible: false,//保存表单时loading框
      dialogCoupon: false,//保存表单时loading框
      dialogCertificate: false,//保存表单时loading框
      columns: [
        {prop: 'userNo', label: '用户编号', sortable: false},
        {prop: 'username', label: '用户名', sortable: false},
        {prop: 'mobile', label: '手机号', sortable: false},
        {prop: 'realName', label: '实名认证', sortable: false},
        // {prop: 'cardId',},
        {prop: 'email', label: '邮箱', sortable: false},
        {prop: 'headPic', label: '用户头像', sortable: false, imgFlag: true},
        {
          prop: 'state', label: '用户状态', sortable: false, tagFlag: true,
          tagFormatter: [
            {text: '正常', value: 1, type: 'success'},
            {text: '冻结', value: 2, type: 'warn'}
          ]
        },
        {
          prop: 'createTime', label: '添加时间', sortable: false, formatter: function (row) {
            return moment(row.createTime).format('YYYY-MM-DD HH:mm:ss');
          }
        },
      ],
      fileList: [],
      // 新增编辑界面数据
      dataForm: {},
      //表单检验规则
      dataFormRules: {},
    }
  },
  created() {
    this.pageRequest.orderParam = this.orderParam
    this.getList();
  },
  methods: {
    formatter(row, column, cellValue, index) {
      console.log(row, column, cellValue, index)
    },
    //获取表格数据
    getList() {
      this.listLoading = true
      //【API请求】----获取表格列表数据
      this.$api.getTbUserList(this.pageRequest).then(response => {
        this.tableList = response.data.content
        this.tableTotal = response.data.total
        this.listLoading = false;
      }).catch((res) => {
        this.$message({message: '列表获取失败', type: 'error'})
      })
    },
    //表格数据筛选
    handleFilter() {
        this.pageRequest = {
            pageNum: 1,
            pageSize: 10,
        }
      this.pageRequest.orderParam = this.orderParam
      this.pageRequest.searchParam = this.searchParam
      this.getList()
    },
    //【按钮点击】--- 弹出新增表单
    handleCreate() {
      this.operation = true;
      this.initDataForm();
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
    },
    //【按钮点击】--- 弹出编辑表单
    handleUpdate(row) {
      this.operation = false;
      this.dataForm = Object.assign({}, row)
      //显示编辑菜单
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
        this.editLoading = false;
      })
      const format = moment(row.createTime).format('YYYY-MM-DD HH:mm:ss');
      this.dataForm.createTime = format
    },
    //保存表单数据
    saveFormData() {
      this.$refs['dataForm'].validate((valid) => {
        if (!valid) {
          return false;
        }
        this.editLoading = true;
        //【API请求】----保存数据
        this.$api.saveTbUser(this.dataForm).then(() => {
          this.editLoading = false;//关闭loading框
          this.dialogFormVisible = false;//关闭表单页面
          this.initDataForm();//重置表单数据
          this.getList();//重新获取表格数据
          this.$notify({title: '成功', message: '保存成功', type: 'success', duration: 2000})
        })
      })
    },
    //【按钮点击】---删除行
    handleDelete(row) {
      this.$confirm('确认删除该记录吗？', '提示', {}).then(() => {
        //【API请求】---- 删除数据
        this.$api.deleteTbUser({ids: row.id}).then(() => {
          this.$message({message: '操作成功', type: 'success'})
            this.pageRequest.pageNum = 1
          this.getList();
        })
      }).catch(() => {
        this.$message({message: '操作失败', type: 'error'})
      });
    },
    //初始化表单数据，重新渲染
    initDataForm() {
      this.dataForm = {
        id: '',
        state: '',
        delFlag: '',
        districtId: '',
        cityId: '',
        provinceId: '',
        openId: '',
        companyId: '',
        coeCompanyId: '',
        email: '',
        password: '',
        userNo: '',
        mobile: '',
        address: '',
        authMessage: '',
        token: '',
        wechatName: '',
        csi: '',
        allAuthority: '',
        orderMessage: '',
        systemMessage: '',
        headPic: '',
        realName: '',
        idCard: '',
        blackEngineerId: '',
        authority: '',
        username: '',
        createDateTime: '',
        updateDateTime: '',
        updateTime: '',
      };
    },
    //关闭表单弹出框
    closeDialog() {
      this.$refs['dataForm'].resetFields();
      this.dialogFormVisible = false
    },

    handleImport(){
      this.dialogImportVisible = true;
    },

    handleExcel(){
      this.$confirm('是否确定导出模板？', '提示', {}).then(() => {
        window.open(this.CMBASE.baseFileContext + "/CM-API/TbUser/indexOfUser")
      }).catch()
    },

    closeImportDialog() {
      this.importFile = []
      this.dialogImportVisible = false;
      this.getList();
    },

    handleCertificate(row){
      this.did=row.id
      this.dialogCertificate = true

    },

    handleCoupon(row){
      this.did=row.id
      this.dialogCoupon = true
    },

    UploadSuccess(){
      this.dialogImportVisible = false ;
      this.$message({
        message: '导入成功',
        type: 'success'
      });
      this.getList();
    },

    UploadError(){
      this.$message({
        message: '导入失败',
        type: 'error'
      });
    },


  }


}
</script>
